<script setup lang="ts">
import { ref } from 'vue'
import { get} from '@/utils/service'
import { VUE_APP_BASE_API} from '@/utils/baseConfig'
import { showNotify } from 'vant'
const valCodeModel = ref({ load: true, butText: '获取验证码', sendStatus: 1, delay: 60 })
const member = ref({})
const noEmpty = ref(false)
const showSignDialog = ref(false)
const showOrHideState = ref(false)
const mobilePhone = ref()
const codeNum = ref()
const loadingStatus=ref(false);
queryCarMasterWechat()
function onClickLeft() {
  window.history.back()
}

function queryCarMasterWechat() {
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  get('/memberWechatNew/queryMemberWehcat', {})
    .then((res) => {
      if (res.code === 0) {
        member.value = res.data
        console.log("member:"+member.value)
        if (member.value == null ||member.value.memAuthStatus==1) {
          noEmpty.value = true
        } else {
          console.log(hideMiddleFour(member.value.mobilePhone))
          member.value.tempPhone=hideMiddleFour(member.value.mobilePhone);
          noEmpty.value = false
        }
      } else {
        noEmpty.value = true
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
function hideMiddleFour(phoneNumber) {
  // 检查电话号码是否为10位数字
  if (phoneNumber.length === 11) {
    return phoneNumber.slice(0, 3) + '****' + phoneNumber.slice(7);
  } else {
    return phoneNumber; // 或者返回错误信息，取决于你的需求
  }
}

function changePop() {
  showSignDialog.value = true
}
function phoneValidator() {
  const state = /^1\d{10}$/.test(mobilePhone.value)
  if (state) {
    valCodeModel.value.load = false
  } else {
    valCodeModel.value.load = true
  }
  return state
}
function codeValidator() {
  return /^[0-9]{4}$/.test(codeNum.value)
}
function sendMobileMessage() {
  const oldPhone=member.value.mobilePhone;
  if(oldPhone==mobilePhone.value){
    showNotify({ type: 'danger', message: "新电话和原来电话号码一致" })
    return ;
  }
  valCodeModel.value.load = true
  valCodeModel.value.butText = '发送中...'
  let delay = valCodeModel.value.delay
  get('/memberWechatNew/sendMobileMessage', { mobilePhone: mobilePhone.value }).then((res) => {
    if (res.code === 0) {
      showNotify({ type: 'success', message: '验证码已发送，请注意查收', duration: 3000 })
      valCodeModel.value.sendStatus = 2
      delay--
      valCodeModel.value.butText = delay + 's后重新获取'
      //最后的innerHTML不能丢，否则delay为一个对象
      if (delay > 0) {
        const timeInt = setInterval(() => {
          valCodeModel.value.butText = delay + 's后重新获取'
          delay--
          if (delay <= 0) {
            clearInterval(timeInt)
            valCodeModel.value.load = false
            valCodeModel.value.sendStatus = 1
            valCodeModel.value.butText = '获取验证码'
            valCodeModel.value.delay = 60
          }
        }, 1000)
      }
    } else {
      showNotify({ type: 'danger', message: res.msg })
      valCodeModel.value.butText = '获取验证码'
    }
  })
}
function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  loadingStatus.value = true // 显示加载状态
  const openId=member.value.openId;
  const tempPhone=values.mobilePhone;
  const oldPhone=member.value.mobilePhone;
  if(tempPhone==oldPhone){
     showNotify({ type: 'danger', message: "新电话和原来电话号码一致" })
     return ;
  }
  try {
    get('/memberWechatNew/saveWechatMobilePhone', {codeNum:values.codeNum,mobilePhone:tempPhone,openId:openId}).then((res) => {
      if (res.code === 0) {
        showNotify({ type: 'success', message: res.msg , duration: 3000 })
        setTimeout(() => {
          window.location.reload();
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function showOrHideMobilePhone(){
  const tempState=showOrHideState.value;
  if(tempState==true){
    showOrHideState.value=false;
  }else{
    showOrHideState.value=true;
  }
}
</script>
<template>
  <van-nav-bar title="更改电话" left-text="返回" left-arrow @click-left="onClickLeft" />
  <van-empty
    v-if="noEmpty == true"
    :image="VUE_APP_BASE_API+'/images/vue/noData.png'"
    image-size="100"
    description="您还未注册会员"
  />
  <div style="text-align: center;justify-content: center;vertical-align: middle;min-height: 400px;">
    <div style="font-size: 38px;font-weight:600;margin-top: 120px;color: var(--sub-one-color);">当前手机号</div>
    <div style="font-size: 32px;font-weight:600;color:var(--main-color);margin-top: 60px;display: flex;justify-content: center;">
      <div v-if="showOrHideState">{{ member.mobilePhone }}</div>
      <div v-else>{{ member.tempPhone }}</div>
      <div @click="showOrHideMobilePhone">
        <img v-if="showOrHideState" :src="VUE_APP_BASE_API+'/images/vue/showEye.png'" style="width: 40px;margin-top: 5px;margin-left: 12px;"></img>
        <img v-else :src="VUE_APP_BASE_API+'/images/vue/hideEye.png'" style="width: 40px;margin-top: 5px;margin-left: 12px;"></img>
      </div>
    </div>
  </div>
  <div style="position: fixed;bottom: 120px;text-align: center;width: 100%;max-width: 1280px;">
    <van-button
        type="success"
        class="buttEdit"
        style="background-color: var(--main-color);min-width: 90%;border-color: var(--main-color);"
        @click="changePop"
        >更改电话号码</van-button
        >
  </div>
  <van-popup
    closeable
    v-model:show="showSignDialog"
    position="bottom"
    round
    :style="{ height: '50%' }"
  >
    <div>
      <h3 style="text-align: center; line-height: 40px; height: 40px">输入新电话</h3>
    </div>
      <div style="text-align: center; margin: auto 12px; padding: 12px">
            <br></br>
             <van-form @failed="onFailed" @submit="submitFrm">
            <van-cell-group inset>
              <van-field
                v-model="mobilePhone"
                label="电话"
                required="true"
                name="mobilePhone"
                placeholder="请输入新电话"
                type="tel"
                :rules="[
                  { required: true, message: '请填写手机号码' },
                  {
                    validator: phoneValidator,
                    message: '请输入正确的手机号格式',
                    trigger: 'onChange',
                  },
                ]"
              />
              <van-field
                required="true"
                v-model="codeNum"
                center
                clearable
                name="codeNum"
                type="number"
                label="验证码"
                placeholder="请输入短信验证码"
                :rules="[
                  { required: true, message: '请输入4位验证码' },
                  { validator: codeValidator, message: '请输入4位验证码', trigger: 'onChange' },
                ]"
              >
                <template #button>
                  <van-button
                    size="small"
                    type="primary"
                    :disabled="valCodeModel.load"
                    @click="sendMobileMessage"
                    >{{ valCodeModel.butText }}</van-button
                  >
                </template>
              </van-field>
            </van-cell-group>
            <br />
            <br />
              <van-button
                round
                block
                type="primary"
                :loading="loadingStatus"
                loading-type="spinner"
                loading-text="提交中..."
                native-type="submit"
              >
                更新
              </van-button>
          </van-form>
      </div>
  </van-popup>
  <br />
</template>
